package znet

import (
	"bytes"
	"encoding/binary"
	"errors"
	"zinx/utils"
	"zinx/ziface"
)

/**
封包拆包的具体模块
*/

type DataPack struct {
}

// 初始化示例
func NewDataPack() *DataPack {
	return &DataPack{}
}

// 获取包的头长度方法
func (d *DataPack) GetHeadLen() uint32 {

	//datalen uint32(4个字节) +id (4个字节)
	return 8
}

// 封包方法
func (d *DataPack) Pack(msg ziface.IMessage) ([]byte, error) {
	//创建bytes字节缓冲
	dataBuf := bytes.NewBuffer([]byte{})
	//将datalen 写入buf
	if err := binary.Write(dataBuf, binary.LittleEndian, msg.GetDataLen()); err != nil {
		return nil, err
	}
	//将msgid写入buf
	if err := binary.Write(dataBuf, binary.LittleEndian, msg.GetMsgId()); err != nil {
		return nil, err
	}
	//将data写入buf
	if err := binary.Write(dataBuf, binary.LittleEndian, msg.GetData()); err != nil {
		return nil, err
	}
	return dataBuf.Bytes(), nil
}

// 拆包方法 先读head 长度 ,根据head 长度读取内容
func (d *DataPack) UnPack(binaryData []byte) (ziface.IMessage, error) {
	//创建bytes字节缓冲
	dataBuf := bytes.NewReader(binaryData)

	//直解压	head 获取datalen 与 msgid
	msg := &Message{}

	//读取datalen
	if err := binary.Read(dataBuf, binary.LittleEndian, &msg.DataLen); err != nil {
		return nil, err
	}
	//读取msgId
	if err := binary.Read(dataBuf, binary.LittleEndian, &msg.Id); err != nil {
		return nil, err
	}
	//判断datalen是否超出最大包的限制
	if utils.GlobalObject.MaxPackageSize > 0 && msg.DataLen > utils.GlobalObject.MaxPackageSize {
		return nil, errors.New("too large data recv")
	}

	return msg, nil
}
